<template>
    <div class="app-container">
        <div class="search-box">
            <!-- 搜索表单 -->
            <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" class="search-form-new">
                <el-form-item label="游戏名称" prop="gameId">
                    <el-select style="width: 100%;" filterable clearable v-model="queryParams.gameId"
                        placeholder="请选择游戏名称">
                        <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="游戏账号" prop="account">
                    <el-input v-model="queryParams.account" placeholder="请输入游戏账号" clearable />
                </el-form-item>
                 <el-form-item label="状态" label-width="68px">
          <el-select v-model="queryParams.rentState" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="1"></el-option>
            <el-option label="已上架" value="2"></el-option>
            <el-option label="出租中" value="3"></el-option>
            <el-option label="已下架" value="4"></el-option>
             <el-option label="审核不通过" value="5"></el-option>
          </el-select>
        </el-form-item>
                <el-form-item label="自编号" prop="selfNumber">
                    <el-input v-model="queryParams.selfNumber" placeholder="请输入自编号" clearable />
                </el-form-item>

                <el-form-item label="关键字" prop="des">
                    <el-input v-model="queryParams.des" placeholder="描述模糊查询" clearable />
                </el-form-item>

                <el-form-item label="是否自营" prop="goodsType">
                    <el-select v-model="queryParams.goodsType" placeholder="请选择" clearable>
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="2"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" type="warning" @click="resetQuery">重置</el-button>
                    <el-button type="primary" icon="el-icon-plus" v-hasPermi="['rentalAccount:add']"
                        @click="openRentalCreate" class="zdy-btn">发布账号</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="table_box table_box_new table-section">

            <!-- 表格数据 -->
            <el-table v-loading="loading" :data="accountList" border style="width: 100%">
                <el-table-column prop="account" label="账号" width="150"></el-table-column>
                <el-table-column prop="gameName" label="游戏名称" width="120"></el-table-column>
                <el-table-column label="区服" width="130" prop="systemName">
              <template slot-scope="scope">
                <span>{{ scope.row.systemName ? scope.row.systemName + '/' : '' }}</span>
                <span>{{ scope.row.carrierName ? scope.row.carrierName + '/' : '' }}</span>
                <span>{{ scope.row.groupName ? scope.row.groupName + '/' : '' }}</span>
                <span>{{ scope.row.serverName }}</span>
              </template>
              
            </el-table-column>
             <el-table-column prop="selfNumber" label="自编号" width="100"></el-table-column>
                <el-table-column prop="status" label="状态" width="120">
                    <template slot-scope="scope">
                        <el-tag :type="statusMap[scope.row.rentState] ? statusMap[scope.row.rentState].type : ''">
                            {{ statusMap[scope.row.rentState] ? statusMap[scope.row.rentState].name : '' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="每时价格" width="100"></el-table-column>
                <el-table-column prop="priceDay" label="每日价格" width="100"></el-table-column>
                <el-table-column prop="priceWeek" label="每周价格" width="100"></el-table-column>
                <el-table-column prop="priceSub" label="预付款" width="100"></el-table-column>
               
                <el-table-column prop="titleImg" label="主图" width="100">
                    <template slot-scope="scope">
                        <imgBox width="50px" height="50" isWrap="nowrap" :img="scope.row.titleImg"></imgBox>
                    </template>
                </el-table-column>
                <el-table-column prop="goodsType" label="是否自营" width="100">
                    <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.goodsType == 1">是</el-tag>
                        <el-tag type="danger" v-if="scope.row.goodsType == 2">否</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="标题" width="150">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" :content="scope.row.title" placement="top-start">
                            <div class="zdy-des">{{ scope.row.title }}</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="des" label="描述" width="180">
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" :content="scope.row.des" placement="top-start">
                            <div class="zdy-des">{{ scope.row.des }}</div>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="发布时间" width="160"></el-table-column>
                <el-table-column prop="createName" label="发布人" width="100"></el-table-column>
                <el-table-column prop="downDes" label="下架原因" width="150"></el-table-column>
                <el-table-column prop="failReason" label="审核拒绝" width="150"></el-table-column>
                <el-table-column prop="downTime" label="下架时间" width="160"></el-table-column>
                <el-table-column prop="remark" label="备注" width="150"></el-table-column>
                <el-table-column label="操作" width="250" fixed="right">
                    <template slot-scope="scope">
                            <el-button  type="add"
                                @click="handleAudit(scope.row)">
                                查看
                        </el-button>
                        <el-button v-if="checkPermi(['rental:edit']) && scope.row.rentState != 3" type="text"
                            @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button v-if="checkPermi(['rental:launch']) && scope.row.rentState == 4" type="add"
                            @click="handleOnline(scope.row)">
                            上架
                        </el-button>
                        <el-button v-if="checkPermi(['rental:down']) && scope.row.rentState == 2" type="del"
                            @click="handleOffline(scope.row)">
                            下架
                        </el-button>
                        <el-button v-if="checkPermi(['rental:rent']) && scope.row.rentState == 2" type="text"
                            @click="handleRent(scope.row)">
                            开始出租
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      
        <!-- 下架弹窗 -->
        <el-dialog title="账号下架" :visible.sync="offlineDialogVisible" width="500px">
            <el-form ref="offlineForm" :model="offlineForm" label-width="100px">
                <el-form-item label="下架原因" required>
                    <el-input type="textarea" :rows="3" placeholder="请输入下架原因" v-model="offlineForm.downDes">
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="offlineDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitOffline">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 租号下单弹窗 -->
        <el-dialog title="租号下单" :visible.sync="rentDialogVisible" width="800px">
            <div class="form-box">
                <!-- 账号信息展示 -->
                <el-descriptions title="账号信息" :column="4" border :labelStyle="{ width: '80px' }">
                    <el-descriptions-item label="游戏">{{ currentAccount.gameName }}</el-descriptions-item>
                    <el-descriptions-item label="账号">{{ currentAccount.account }}</el-descriptions-item>
                  
                    <el-descriptions-item :span="3" label="区服">
                        {{ currentAccount.systemName}}
                        <span v-if="currentAccount.systemName">/</span>
                        {{ currentAccount.carrierName}}
                        <span v-if="currentAccount.carrierName">/</span>
                        {{ currentAccount.groupName }}
                         <span v-if="currentAccount.groupName">/</span>
                        {{ currentAccount.serverName }}</el-descriptions-item>
                     <!-- <el-descriptions-item label="主图">
                        <imgBox width="50px" height="50" isWrap="nowrap" :img="currentAccount.titleImg">
                        </imgBox>
                    </el-descriptions-item> -->
                    <el-descriptions-item :span="6" label="描述">{{ currentAccount.des }}</el-descriptions-item>
                </el-descriptions>

                <!-- 下单表单 -->
                <el-form ref="rentForm" :model="rentForm" :rules="rentRules" label-width="100px"
                    style="margin-top: 20px;">
                    <el-form-item label="租号人" prop="useUserId">
                        <virtual-select style="width: 250px;" @change="sellerChange" v-model="rentForm.useUserId" :list="userList" label="nickName" value="userId"
                            :placeholder="'输入关键字用于租号人'" :keeps-params="20" :is-concat="false" :concat-symbol="' || '"
                            :is-multiple="false" :disabled="false" :allow-create="false" />
                    </el-form-item>

                    <el-form-item label="租赁方式" prop="rentType">
                        <el-radio-group v-model="rentForm.rentType" @change="handleRentTypeChange">
                            <el-radio :label="1">时租 ({{ currentAccount.price }}元)</el-radio>
                            <el-radio :label="2">日租 ({{ currentAccount.priceDay }}元)</el-radio>
                            <el-radio :label="3">周租 ({{ currentAccount.priceWeek }}元)</el-radio>
                        </el-radio-group>
                    </el-form-item>


                    <el-form-item label="小时数" prop="rentLength">
                        <el-input-number style="width: 240px;" v-if="rentForm.rentType === 1"
                            v-model="rentForm.rentLength" :min="1" :max="24" @change="calculateAmount"
                            controls-position="right">
                        </el-input-number>
                        <div v-else> {{ rentForm.rentType == 2 ? 24 : 168 }}小时</div>
                    </el-form-item>
                    <div class="flex between">
                        <div>预付款
                            <span>{{ rentForm.priceSub }}</span>元</div>
                        <div class="betweens">租金
                            <span>{{ rentForm.rentAmount }}</span>元</div>
                    </div>
                 
                    <div class="footers">
                        总金额 <span>{{rentForm.priceTotal}}</span>元
                    </div>
                    <!-- <el-form-item label="总金额" prop="priceTotal">
                        <el-input v-model="rentForm.priceTotal" disabled></el-input>
                    </el-form-item> -->
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="rentDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitRentOrder">提 交</el-button>
                </div>
            </div>
        </el-dialog>

        <retalDetail ref="retalDetailRef"></retalDetail>
        <retalCreate v-if="retalShow" ref="retalCreateRef" @success="handleQuery" @close="retalClose"></retalCreate>
    </div>
</template>

<script>
import VirtualSelect from "@/components/VirtualSelect.vue";

import supplyConfigApi from "@/api/system/supplyConfig";
import { rentalList, rentalTakeUp, rentalTakeDown , rentalCreateOrder } from "@/api/rental/account";
import retalCreate from "./components/retalCreate.vue";
import retalDetail from "./components/retalDetail.vue";
import Pagination from "@/components/Pagination";
export default {
    // name: "RentalAccount",
    components: { Pagination, retalCreate, VirtualSelect , retalDetail },
    data() {
        return {
            retalShow: false,
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 账号表格数据
            accountList: [],
            // 游戏列表
            gameList: [],
            // 用户列表
            userList: [],

            
            statusMap: {
                1: {
                    name: "待审核",
                    type: "warning",
                },
                2: {
                    name: "已上架",
                    type: "success",
                },
                3: {
                    name: "出租中",
                    type: "warning",
                },
                4: {
                    name: "已下架",
                    type: "danger",
                },
                5: {
                    name: "审核不通过",
                    type: "danger",
                },
            },

            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                gameId: '',
                account: '',
                selfNumber: '',
                des: '',
                goodsType: ''
            },
            // 审核表单
            auditForm: {
                id: null,
                result: 1,
                reason: null
            },
            // 下架表单
            offlineForm: {
                id: null,
                downDes: null
            },
            // 租号表单
            rentForm: {
                goodsId:'',
                accountId: null,
                useUserId: null,
                rentUserName:'',
                sourceScene:2,
                 rentLength: 1,
                 qufu:'',
                rentType: 1,
                priceSub: 0,
                rentAmount: 0,
                priceTotal: 0
            },
            // 表单校验
            rentRules: {
                useUserId: [{ required: true, message: "请选择租号人", trigger: "blur" }],
                rentType: [{ required: true, message: "请选择租赁方式", trigger: "change" }],
                rentLength: [{ required: true, message: "请输入数量", trigger: "blur" }]
            },
            // 当前选中账号
            currentAccount: {},
            // 弹窗显示控制
            auditDialogVisible: false,
            offlineDialogVisible: false,
            rentDialogVisible: false,


        };
    },
    computed: {
        allGameList() {
            return this.$store.getters.allGameList;
        },
    },
    created() {
        this.getList();
    },
    methods: {
        sellerChange(val) {
             const user = this.userList.find(item => item.userId == val);
               if (user) {
                    this.rentForm.useUserId = user.userId;
                    this.rentForm.useUserName = user.nickName;
                    console.log(this.rentForm.rentUserName, this.rentForm.useUserId)
                }
        },
        openRentalCreate() {
            this.retalShow = true
            this.$nextTick(() => {
                this.$refs.retalCreateRef.open("add");
            })
        },
        /** 查询账号列表 */
        getList() {
            this.loading = true;
            rentalList(this.queryParams).then(response => {
                this.accountList = response.rows;
                this.total = response.total;
            }).finally(() => {
                this.loading = false;
            });
        },
        /** 查询游戏列表 */
        getGameList() {
            listGame().then(response => {
                this.gameList = response.rows;
            });
        },
        /** 查询用户列表 */
        getUserList() {
            supplyConfigApi.getAllUserList().then((res) => {
                this.userList = res.rows || [];
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            // this.queryParams.pageSize = 10
            // this.queryParams.pageNum = 1
            this.handleQuery();
        },
        /** 审核按钮操作 */
        handleAudit(row) {
            
            this.$refs.retalDetailRef.open(row)
        },
        /** 提交审核 */
        submitAudit() {
            const params = {
                id: this.auditForm.id,
                status: this.auditForm.result === 1 ? 1 : 4,
                reason: this.auditForm.reason
            };

        },
        retalClose() {
            this.retalShow = false
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.retalShow = true
            this.$nextTick(() => {
                this.$refs.retalCreateRef.open("edit", row.id);
            })

        },
        /** 下架按钮操作 */
        handleOffline(row) {
            this.offlineForm.id = row.id;
            this.offlineForm.downDes = "";
            this.offlineDialogVisible = true;
        },
        /** 提交下架 */
        submitOffline() {
            this.$refs["offlineForm"].validate(valid => {
                if (valid) {
                    rentalTakeDown(this.offlineForm).then(() => {
                        this.$message.success('下架成功'); this.getList();
                        this.offlineDialogVisible = false
                    });
                }
            });
        },
        /** 上架按钮操作 */
        handleOnline(row) {
            let cont = '确定上架游戏账号' + row.account + '吗？';
            this.$confirm(cont).then(() => {
                rentalTakeUp(row.id).then(() => { this.$message.success('上架成功'); this.getList(); });
            });

        },
        /** 开始出租按钮操作 */
        async handleRent(row) {
            await this.getUserList();
            this.currentAccount = row;
            this.rentForm = {
                sourceScene:2, 
                useUserName:'',
                goodsId: row.id,
                useUserId: '',
                rentUserName:'',
                rentType: 1,
                rentLength: 1,
                price: row.price || 0,
                priceDay: row.priceDay || 0,
                priceWeek: row.priceWeek || 0,
                priceSub: row.priceSub || 0,
                rentAmount: 0,
                priceTotal: 0,
               
            };
       const parts = [];


if (row.systemName) {

  parts.push(row.systemName, row.carrierName, row.groupName, row.serverName);
} else if (row.carrierName) {
 
  parts.push(row.carrierName, row.groupName, row.serverName);
} else if (row.groupName) {

  parts.push(row.groupName, row.serverName);
} else {

  parts.push(row.serverName);
}

this.rentForm.qufu = parts.filter(Boolean).join('') || '';
            this.calculateAmount()
            // 显示弹窗
            this.rentDialogVisible = true;

        },
        /** 租赁方式变化 */
        handleRentTypeChange(value) {
            if(value == 1) {
                this.rentForm.rentLength = 1
            }else if(value == 2) {
                this.rentForm.rentLength =24
            }else if(value == 3) {
                this.rentForm.rentLength =168
            }
            this.calculateAmount();
        },

        /** 计算金额 */
        calculateAmount() {
            //代表日租
            if (this.rentForm.rentType == 1) {
                this.rentForm.rentAmount = this.rentForm.price * this.rentForm.rentLength;
                this.rentForm.priceTotal = this.rentForm.rentAmount + this.rentForm.priceSub;
            } else if (this.rentForm.rentType == 2) {
                this.rentForm.rentAmount = this.rentForm.priceDay;
                this.rentForm.priceTotal = this.rentForm.rentAmount + this.rentForm.priceSub;
            } else {
                this.rentForm.rentAmount = this.rentForm.priceWeek;
                this.rentForm.priceTotal = this.rentForm.rentAmount + this.rentForm.priceSub;
            }

        },
        /** 提交租号订单 */
        submitRentOrder() {
            this.$refs.rentForm.validate(valid => {
                if (valid) {
                    rentalCreateOrder(this.rentForm).then(() => {
                        this.$message.success('提交成功');
                        this.rentDialogVisible = false
                        setTimeout(() => {
                            this.$router.push({
                                path: "/rental/rentalOrder",
                            });
                        }, 500);
                         this.getList();
                    });
                }
            });
        }
    }
};
</script>

<style scoped lang="scss">
.search-form {
    margin-bottom: 20px;
}
.between {
    font-weight: 600;
    margin-left: 50px;
    margin-bottom: 20px;
    span {
        
        font-size: 16px;
    }
    .betweens {
        margin-left: 20px;
    }
}
.footers {
    text-align: right;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 20px;
    span {
        color: #ff0000;
        font-size: 18px;
    }
}
</style>